import { useEffect, useRef } from 'react'
const {remote} = window.require('electron');
const { Menu, MenuItem } = remote;

const useContextMenu = (itemArr,targetSelector) => {
  const clickedElement = useRef(null)
  useEffect(() => {
    const menu = new Menu({});
    itemArr.forEach(item => {
      menu.append(new MenuItem(item))

    });
    const handleContexMenu = (e) => {
      if (document.querySelector(targetSelector).contains(e.target)) {
        clickedElement.current = e.target;
        menu.popup({
          window: remote.getCurrentWindow(),
        })
      }

    }

    window.addEventListener('contextmenu', handleContexMenu)
    return () => {
      window.removeEventListener('contextmenu', handleContexMenu)
    }

  })
  return clickedElement
}

export default useContextMenu